import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Input, Select, Space, Card, Divider, Typography, message, Popconfirm } from 'antd';
import {
  SearchOutlined, UndoOutlined, EditOutlined, DeleteOutlined,
  CheckCircleOutlined, CloseCircleOutlined, SyncOutlined, ClockCircleOutlined,
  AuditOutlined
} from '@ant-design/icons';
import ProductAllInfosPage from './productInfos';
import { useModel } from '@umijs/max';
import { page, productProcess, removeProduct } from '@/services/apis/serviceProviderRegister';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 状态选项（含状态跳转机制对应的所有可能状态）
const STATUS_OPTIONS = [
  { value: '待%审核', label: '待审核' },
  { value: '审核通过', label: '已通过' },
  { value: '审核不通过', label: '不通过' },
  { value: '审核退回', label: '已退回' },
  // { value: 'in_progress', label: '进行中' },
];

// 新增：办理进度列表列配置
const progressColumns = [
  {
    title: (
      <Space align="center">
        {/* <ClockCircleOutlined /> */}
        <span>时间</span>
      </Space>
    ),
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 200,
    align: 'center',
  },
  {
    title: '单位',
    dataIndex: 'departmentName',
    key: 'departmentName',
    width: 200,
    align: 'center',
  },
  {
    title: '环节',
    dataIndex: 'link',
    key: 'link',
    width: 200,
    align: 'center',
  },
  {
    title: '结果',
    dataIndex: "resultStatus",
    key: 'resultStatus',
    width: 200,
    align: 'center',
    render: (status: string) => getStatusText(status),
  },
  {
    title: '意见',
    dataIndex: 'auditRemark',
    key: 'auditRemark',
    width: 200,
    render: (opinion: string) => (
      <Text>
        {opinion}
      </Text>
    ),
  },
];

// 根据状态值获取显示文本（带颜色标识）
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return <Text >待审核</Text>;
    case 'approved':
      return <Text >已通过</Text>;
    case 'rejected':
      return <Text>不通过</Text>;
    case 'returned':
      return <Text >已退回</Text>;
    case 'processing':
      return <Text >进行中</Text>;
    default:
      return <Text>{status}</Text>;
  }
};

const ProductSolutionManagement: React.FC = () => {
  // 状态管理：新增进度弹窗状态和进度列表数据
  const [productList, setProductList] = useState([]);
  const [searchForm] = Form.useForm(); // 搜索表单
  const [currentProduct, setCurrentProduct] = useState<any>(null); // 当前操作的产品
  const {
    modalProps,
    setModalProps,
  } = useModel("ProductManager.modal")
  const { initialState, setInitialState } = useModel('@@initialState');
  const [modalVisible, setModalVisible] = useState({
    edit: false, // 编辑弹窗
    review: false, // 审核弹窗
    progress: false, // 新增：进度弹窗
  });
  const [pagination, setPagination] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [currentProgressList, setCurrentProgressList] = useState<any[]>([]); // 新增：当前产品的进度列表

  // ---------------------- 新增：打开进度弹窗 ----------------------
  const handleProgressOpen = (record: any) => {

    productProcess({ id: record.id }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setCurrentProduct(record);
        setCurrentProgressList([data]);
      }
    })
    // setCurrentProduct(record);
    setModalVisible({
      ...modalVisible,
      progress: true
    });
  };

  // 1. 搜索功能：根据产品名称和状态筛选
  const handleSearch = async () => {
    const searchValues = await searchForm.validateFields();
    searchFunction({ ...searchValues, current: pagination.current, pageSize: pagination.pageSize })
  };

  // 2. 重置搜索：恢复初始列表
  const handleReset = () => {
    searchForm.resetFields();
    searchFunction({ current: pagination.current, pageSize: pagination.pageSize })
  };

  // 3. 删除产品：从列表中移除该记录

  const handleDelete = (id: string) => {
    removeProduct({ id }).then(res => {
      const { code } = res;
      if (code == 0) {
        searchFunction({ ...searchForm.getFieldsValue(), current: pagination.current, size: pagination.pageSize })
      }
    })
  };

  // 4. 打开编辑弹窗：加载当前产品信息
  const handleEditOpen = (product: any) => {
    setModalProps(prev => ({ ...prev, visible: true, record: product, title: "编辑产品信息" }))
    // setCurrentProduct(product);
  };

  const searchFunction = (values: any) => {
    page({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
    }).then(res => {
      const { code, data } = res;
      if (code == 0) {
        // //message.success("查询成功")
        setProductList(data.records || [])
        setPagination({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
      }
    })
  }


  useEffect(() => {
    searchFunction({ current: pagination.current, pageSize: pagination.pageSize })
  }, [])

  // 6. 打开审核弹窗：加载当前产品信息（与“我的待办”审核逻辑一致）
  const handleReviewOpen = (product: any) => {
    setModalProps(prev => ({ ...prev, visible: true, record: product, title: "审核产品" }))
  };

  // 表格列配置：新增“进度”按钮（在“审核”后）
  const tableColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: "10%",
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: "15%",
      ellipsis: true
    },
    {
      title: '服务商名称',
      dataIndex: 'supplierName',
      key: 'supplierName',
      width: "15%",
      ellipsis: true
    },
    {
      title: '产品简介',
      dataIndex: 'productEvaluation',
      key: 'productEvaluation',
      width: "15%",
      ellipsis: true
      // 简介过长时省略显示
      // render: (text: string) => <Text ellipsis={{ rows: 1 }}>{text}</Text>,
    },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: "10%",
      align: 'center',
      ellipsis: true
    },
    {
      title: '状态',
      dataIndex: 'resultStatus',
      key: 'resultStatus',
      width: "10%",
      align: 'center',
      ellipsis: true,
      // render: (status: string) => getStatusText(status),
    },
    {
      title: '操作',
      key: 'operation',
      width: "30%",
      align: 'center',
      render: (_: any, record: any) => (
        <Space size={2}>
          {/* 删除按钮 */}
          <Popconfirm title="是否删除" onConfirm={() => handleDelete(record.id)}>
            <Button
              type="primary"
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>

          {/* 编辑按钮 */}
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            // disabled={record.auditStatus != 'pending'}
            disabled={record.resultStatus != "待市经信局审核"}
            onClick={() => handleEditOpen(record)}
          >
            编辑
          </Button>
          {/* 审核按钮：仅“待审核”状态可点击 */}
          <Button
            type="primary"
            size="small"
            // disabled={record.status !== 'pending'}
            icon={<AuditOutlined />}
            // disabled={record.resultStatus != 'pending'}
            disabled={record.resultStatus != "待市经信局审核"}
            onClick={() => handleReviewOpen(record)}
          >
            审核
          </Button>
          {/* 新增：进度按钮（所有状态可点击） */}
          <Button
            type="primary"
            size="small"
            icon={<ClockCircleOutlined />}
            // disabled={record.resultStatus == 'pending'}
            onClick={() => handleProgressOpen(record)}
          >
            进度
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      {/* 页面标题 */}
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        产品和解决方案管理
      </div>

      {/* 第一部分：搜索栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
        >
          <Form.Item
            name="productName"
            label="产品名称"
            rules={[{ whitespace: true, message: '请输入有效名称' }]}
          >
            <Input
              placeholder="请输入产品名称"
              style={{ width: '220px' }}
            />
          </Form.Item>
          <Form.Item name="auditStatus" label="状态">
            <Select
              placeholder="请选择状态"
              style={{ width: '180px' }}
              allowClear
            >
              {STATUS_OPTIONS.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset} icon={<UndoOutlined />}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card
        style={{
          borderRadius: 12,
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
          // overflowY: 'auto', // 内部滚动
          padding: '24px',
        }}
      >
        {/* 第二部分：产品列表 */}
        <Table
          columns={tableColumns as any}
          dataSource={productList}
          rowKey="id"
          pagination={{ pageSize: pagination.pageSize, current: pagination.current, total: pagination.total, showSizeChanger: true }}
          bordered
          scroll={{ y: 'calc(100vh - 450px)' }}
          locale={{ emptyText: '暂无产品数据' }}
        />
      </Card>
      <ProductAllInfosPage searchCallFun={handleSearch} />

      {/* ---------------------- 新增：产品办理进度弹窗 ---------------------- */}
      <Modal
        title={`${currentProduct?.productName || '产品'}办理进度`}
        open={modalVisible.progress}
        onCancel={() => setModalVisible({ ...modalVisible, progress: false })}
        maskClosable={false}
        width={900}
        footer={[
          <Button key="close" onClick={() => setModalVisible({ ...modalVisible, progress: false })}>
            关闭
          </Button>
        ]}
        bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
      >
        <Card bordered={false}>
          <Table
            columns={progressColumns as any}
            dataSource={currentProgressList}
            rowKey="id"
            pagination={false} // 进度列表不分页，完整展示
            bordered
            className="custom-table"

            locale={{ emptyText: '暂无该产品的办理进度记录' }}
            rowClassName={() => 'hover:bg-gray-50'} // 行悬浮高亮
          />
        </Card>
      </Modal>
    </div>
  );
};

export default ProductSolutionManagement;